/*
 * @(#)DmsQueryRecordDAObject.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.dao;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import oracle.sql.BLOB;

import com.dcivision.dms.bean.DmsQueryRecord;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.web.ListDmsDocumentForm;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.AbstractBaseObject;
import com.dcivision.framework.dao.AbstractDAObject;
import com.dcivision.framework.web.AbstractSearchForm;

/**
  DmsQueryRecordDAObject.java
  This class is the data access bean for table "DMS_QUERY_RECORD".
  @author      Jenny LI
  @company     DCIVision Limited
  @creation date   30/08/2004
  @version     $Revision: 1.12 $
 */

public class DmsQueryRecordDAObject extends AbstractDAObject {

  public static final String REVISION = "$Revision: 1.12 $";

  public static final String TABLE_NAME = "DMS_QUERY_RECORD";

  public DmsQueryRecordDAObject(SessionContainer sessionContainer,
                             Connection dbConn) {
    super(sessionContainer, dbConn);
  }

  protected void initDBSetting() {
    this.baseTableName = TABLE_NAME;
    this.vecDBColumn.add("ID");
    this.vecDBColumn.add("USER_RECORD_ID");
    this.vecDBColumn.add("QUERY_NAME");
    this.vecDBColumn.add("DESCRIPTION");
    this.vecDBColumn.add("IS_PUBLIC");
    this.vecDBColumn.add("XML_QUERY");
    this.vecDBColumn.add("RECORD_STATUS");
    this.vecDBColumn.add("UPDATE_COUNT");
    this.vecDBColumn.add("CREATOR_ID");
    this.vecDBColumn.add("CREATE_DATE");
    this.vecDBColumn.add("UPDATER_ID");
    this.vecDBColumn.add("UPDATE_DATE");
  }

  protected synchronized AbstractBaseObject getByID(Integer id) throws
    ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    synchronized (dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.USER_RECORD_ID, A.QUERY_NAME, A.DESCRIPTION, A.IS_PUBLIC, A.XML_QUERY, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   DMS_QUERY_RECORD A ");
        sqlStat.append("WHERE  A.ID = ? AND A.RECORD_STATUS = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, id);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        if (rs.next()) {
          DmsQueryRecord tmpDmsQueryRecord = new DmsQueryRecord();
          tmpDmsQueryRecord.setID(getResultSetInteger(rs, "ID"));
          tmpDmsQueryRecord.setUserRecordID(getResultSetInteger(rs, "USER_RECORD_ID"));
          tmpDmsQueryRecord.setQueryName(getResultSetString(rs, "QUERY_NAME"));
          tmpDmsQueryRecord.setDescription(getResultSetString(rs, "DESCRIPTION"));
          tmpDmsQueryRecord.setIsPublic(getResultSetString(rs, "IS_PUBLIC"));
          tmpDmsQueryRecord.setXmlQuery(getResultSetObject(rs, "XML_QUERY"));
          tmpDmsQueryRecord.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpDmsQueryRecord.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpDmsQueryRecord.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpDmsQueryRecord.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpDmsQueryRecord.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpDmsQueryRecord.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpDmsQueryRecord.setCreatorName(UserInfoFactory.getUserFullName(tmpDmsQueryRecord.getCreatorID()));
          tmpDmsQueryRecord.setUpdaterName(UserInfoFactory.getUserFullName(tmpDmsQueryRecord.getUpdaterID()));
          return (tmpDmsQueryRecord);
        } else {
          throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try {
          rs.close();
        } catch (Exception ignore) {} finally {
          rs = null;
        }
        try {
          preStat.close();
        } catch (Exception ignore) {} finally {
          preStat = null;
        }
      }
    }
  }

  protected synchronized List getList(AbstractSearchForm searchForm) throws
    ApplicationException {
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());
    ListDmsDocumentForm docSearchForm = (ListDmsDocumentForm) searchForm;
    Timestamp currTime = Utility.getCurrentTimestamp();
    Timestamp oneDayBeforeCurrTime = Utility.addDay(currTime, -1);
    int fieldNo = 6; //at least six field is need for the prepare statement

    if(!SystemParameterFactory.getSystemParameterBoolean(SystemParameterConstant.DMS_SHOW_EXPIRE_DOC)){
      fieldNo =6;
    }else{
      fieldNo = 3;
    }

    DocumentRetrievalManager documentRetrievalManager = new DocumentRetrievalManager(sessionContainer, dbConn);

    synchronized (dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.USER_RECORD_ID, A.QUERY_NAME, A.DESCRIPTION, A.IS_PUBLIC, A.XML_QUERY, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   DMS_QUERY_RECORD A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
        sqlStat.append("AND (A.IS_PUBLIC='Y' OR CREATOR_ID=?) ");

        // Form the WHERE clause for filtering.
        /*
        if (searchForm.isSearchable()) {
          String searchField = searchForm.getBasicSearchField();
          if (searchField.indexOf(".") < 0) {
            searchField = "A." + searchField;
          }
          sqlStat.append("AND  " + searchField + " " +
                         searchForm.getBasicSearchType() + " ? ");
          fieldNo++;
        }*/
        
        if (searchForm.isSearchable()) {
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
          fieldNo++;
        }

        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            sortAttribute = "A." + sortAttribute;
          }
          sqlStat.append(" ORDER BY "+sortAttribute + " " + searchForm.getSortOrder());

        }

        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 2, sessionContainer.getUserRecordID());
        
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
            this.setPrepareStatement(preStatCnt, 3, searchKeyword);
        }

        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
        try {
          rsCnt.close();
        } catch (Exception ignore) {} finally {
          rsCnt = null;
        }
        try {
          preStatCnt.close();
        } catch (Exception ignore) {} finally {
          preStatCnt = null;
        }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, sessionContainer.getUserRecordID());
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
            this.setPrepareStatement(preStat, 3, searchKeyword);
        }
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);
        while (rs.next() && rowLoopCnt < pageSize) {
          try {
            DmsQueryRecord tmpDmsQueryRecord = new DmsQueryRecord();
            tmpDmsQueryRecord.setID(getResultSetInteger(rs, "ID"));
            tmpDmsQueryRecord.setUserRecordID(getResultSetInteger(rs, "USER_RECORD_ID"));
            tmpDmsQueryRecord.setQueryName(getResultSetString(rs, "QUERY_NAME"));
            tmpDmsQueryRecord.setDescription(getResultSetString(rs, "DESCRIPTION"));
            tmpDmsQueryRecord.setIsPublic(getResultSetString(rs, "IS_PUBLIC"));
            try{
              tmpDmsQueryRecord.setXmlQuery(getResultSetObject(rs, "XML_QUERY"));//Update By Jim Zhou     2006/12/29      EIP-1279
            } catch (Exception ex){
              tmpDmsQueryRecord.setXmlQuery(null);
            }
            tmpDmsQueryRecord.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
            tmpDmsQueryRecord.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
            tmpDmsQueryRecord.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
            tmpDmsQueryRecord.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
            tmpDmsQueryRecord.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
            tmpDmsQueryRecord.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
            tmpDmsQueryRecord.setCreatorName(UserInfoFactory.getUserFullName(tmpDmsQueryRecord.getCreatorID()));
            tmpDmsQueryRecord.setUpdaterName(UserInfoFactory.getUserFullName(tmpDmsQueryRecord.getUpdaterID()));
            tmpDmsQueryRecord.setRecordCount(totalNumOfRecord);
            tmpDmsQueryRecord.setRowNum(startOffset++);
            ++rowLoopCnt;
            result.add(tmpDmsQueryRecord);
          }catch (Exception ex) {
            log.warn("Database has dirty records, ignore these records", ex);
          } 
        }
        return (result);
//      } catch (ApplicationException appEx) {
//        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try {
          rs.close();
        } catch (Exception ignore) {} finally {
          rs = null;
        }
        try {
          preStat.close();
        } catch (Exception ignore) {} finally {
          preStat = null;
        }
        try {
          rsCnt.close();
        } catch (Exception ignore) {} finally {
          rsCnt = null;
        }
        try {
          preStatCnt.close();
        } catch (Exception ignore) {} finally {
          preStatCnt = null;
        }
      }
    }
  }

  protected synchronized List getList() throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();
    Timestamp currTime = Utility.getCurrentTimestamp();
    Timestamp oneDayBeforeCurrTime = Utility.addDay(currTime, -1);
    synchronized (dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.USER_RECORD_ID, A.QUERY_NAME, A.DESCRIPTION, A.IS_PUBLIC, A.XML_QUERY, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   DMS_QUERY_RECORD A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);

        rs = preStat.executeQuery();
        while (rs.next()) {
          DmsQueryRecord tmpDmsQueryRecord = new DmsQueryRecord();
          tmpDmsQueryRecord.setID(getResultSetInteger(rs, "ID"));
          tmpDmsQueryRecord.setUserRecordID(getResultSetInteger(rs, "USER_RECORD_ID"));
          tmpDmsQueryRecord.setQueryName(getResultSetString(rs, "QUERY_NAME"));
          tmpDmsQueryRecord.setDescription(getResultSetString(rs, "DESCRIPTION"));
          tmpDmsQueryRecord.setIsPublic(getResultSetString(rs, "IS_PUBLIC"));
          tmpDmsQueryRecord.setXmlQuery(getResultSetObject(rs, "XML_QUERY"));
          tmpDmsQueryRecord.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpDmsQueryRecord.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpDmsQueryRecord.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpDmsQueryRecord.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpDmsQueryRecord.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpDmsQueryRecord.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpDmsQueryRecord.setCreatorName(UserInfoFactory.getUserFullName(tmpDmsQueryRecord.getCreatorID()));
          tmpDmsQueryRecord.setUpdaterName(UserInfoFactory.getUserFullName(tmpDmsQueryRecord.getUpdaterID()));
          result.add(tmpDmsQueryRecord);
        }
        return (result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try {
          rs.close();
        } catch (Exception ignore) {} finally {
          rs = null;
        }
        try {
          preStat.close();
        } catch (Exception ignore) {} finally {
          preStat = null;
        }
      }
    }
  }

  protected void validateInsert(AbstractBaseObject obj) throws ApplicationException {
    DmsQueryRecord curQueryRecord = (DmsQueryRecord) obj;

    // check duplicate name of same level if config file defined
    log.debug(".................................No duplicate name exists");

  }

  protected void validateUpdate(AbstractBaseObject obj) throws ApplicationException {
  }

  protected void validateDelete(AbstractBaseObject obj) throws ApplicationException {
  }

  protected synchronized AbstractBaseObject insert(AbstractBaseObject obj) throws
    ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    DmsQueryRecord tmpDmsQueryRecord = (DmsQueryRecord) ( (DmsQueryRecord) obj).clone();

    synchronized (dbConn) {
      try {
        Integer nextID = getNextPrimaryID();
        Timestamp currTime = Utility.getCurrentTimestamp();
        if (DataSourceFactory.DB_ORACLE!=DataSourceFactory.getDatabaseType()) {
          sqlStat.append("INSERT ");
          sqlStat.append("INTO   DMS_QUERY_RECORD(ID, USER_RECORD_ID, QUERY_NAME, DESCRIPTION, IS_PUBLIC, XML_QUERY, RECORD_STATUS, UPDATE_COUNT, CREATOR_ID, CREATE_DATE, UPDATER_ID, UPDATE_DATE) ");
          sqlStat.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
          preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
          setPrepareStatement(preStat, 1, nextID);
          setPrepareStatement(preStat, 2, tmpDmsQueryRecord.getUserRecordID());
          setPrepareStatement(preStat, 3, tmpDmsQueryRecord.getQueryName());
          setPrepareStatement(preStat, 4, tmpDmsQueryRecord.getDescription());
          setPrepareStatement(preStat, 5, tmpDmsQueryRecord.getIsPublic());
          setPrepareStatement(preStat, 6, tmpDmsQueryRecord.getXmlQuery());
          setPrepareStatement(preStat, 7, GlobalConstant.RECORD_STATUS_ACTIVE);
          setPrepareStatement(preStat, 8, new Integer(0));
          setPrepareStatement(preStat, 9, sessionContainer.getUserRecordID());
          setPrepareStatement(preStat, 10, currTime);
          setPrepareStatement(preStat, 11, sessionContainer.getUserRecordID());
          setPrepareStatement(preStat, 12, currTime);
          preStat.executeUpdate();
        }else{
          sqlStat.append("INSERT ");
          sqlStat.append("INTO   DMS_QUERY_RECORD(ID, USER_RECORD_ID, QUERY_NAME, DESCRIPTION, IS_PUBLIC, XML_QUERY, RECORD_STATUS, UPDATE_COUNT, CREATOR_ID, CREATE_DATE, UPDATER_ID, UPDATE_DATE) ");
          sqlStat.append("VALUES (?, ?, ?, ?, ?, EMPTY_BLOB(), ?, ?, ?, ?, ?, ?) ");
          preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
          setPrepareStatement(preStat, 1, nextID);
          setPrepareStatement(preStat, 2, tmpDmsQueryRecord.getUserRecordID());
          setPrepareStatement(preStat, 3, tmpDmsQueryRecord.getQueryName());
          setPrepareStatement(preStat, 4, tmpDmsQueryRecord.getDescription());
          setPrepareStatement(preStat, 5, tmpDmsQueryRecord.getIsPublic());
          setPrepareStatement(preStat, 6, GlobalConstant.RECORD_STATUS_ACTIVE);
          setPrepareStatement(preStat, 7, new Integer(0));
          setPrepareStatement(preStat, 8, sessionContainer.getUserRecordID());
          setPrepareStatement(preStat, 9, currTime);
          setPrepareStatement(preStat, 10, sessionContainer.getUserRecordID());
          setPrepareStatement(preStat, 11, currTime);
          preStat.executeUpdate(); 
          preStat.close();
          
          ResultSet rs = null;
          BLOB blob = null;
          sqlStat = new StringBuffer();
          sqlStat.append("SELECT  XML_QUERY ");
          sqlStat.append("FROM  DMS_QUERY_RECORD ");
          sqlStat.append("WHERE ID = " + nextID);
          preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
          rs = preStat.executeQuery();
          if (rs.next()) {
            blob = (BLOB)rs.getBlob("XML_QUERY");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
              ObjectOutputStream out = new ObjectOutputStream(baos);
              out.writeObject(tmpDmsQueryRecord.getXmlQuery());
              out.flush();
            } catch (java.io.IOException ioe) {
              log.error("Cannot write object stream", ioe);
              new java.sql.SQLException("Cannot write object stream");
            }
            blob.putBytes(1, baos.toByteArray());
            
            sqlStat = new StringBuffer();
            sqlStat.append("UPDATE  DMS_QUERY_RECORD ");
            sqlStat.append("SET XML_QUERY = ? ");
            sqlStat.append("WHERE ID = ? ");
            PreparedStatement preStat2 = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            preStat2.setBlob(1, blob);
            preStat2.setInt(2, nextID.intValue());
            preStat2.executeUpdate();
            try { preStat2.close(); } catch (Exception ignore) {} finally {preStat2 = null; }
          }
          try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        }
        tmpDmsQueryRecord.setID(nextID);
        tmpDmsQueryRecord.setCreatorID(sessionContainer.getUserRecordID());
        tmpDmsQueryRecord.setCreateDate(currTime);
        tmpDmsQueryRecord.setUpdaterID(sessionContainer.getUserRecordID());
        tmpDmsQueryRecord.setUpdateDate(currTime);
        tmpDmsQueryRecord.setUpdateCount(new Integer(0));
        tmpDmsQueryRecord.setCreatorName(UserInfoFactory.getUserFullName(tmpDmsQueryRecord.getCreatorID()));
        tmpDmsQueryRecord.setUpdaterName(UserInfoFactory.getUserFullName(tmpDmsQueryRecord.getUpdaterID()));
        return (tmpDmsQueryRecord);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_INSERT_ERROR, e);
      } finally {
        try {
          preStat.close();
        } catch (Exception ignore) {} finally {
          preStat = null;
        }
      }
    }
  }

  protected synchronized AbstractBaseObject update(AbstractBaseObject obj) throws
    ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    DmsQueryRecord tmpQueryRecord = (DmsQueryRecord) ( (DmsQueryRecord) obj).clone();

    synchronized (dbConn) {
      try {
        int updateCnt = 0;
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("UPDATE DMS_QUERY_RECORD ");
        sqlStat.append("SET    USER_RECORD_ID=?, QUERY_NAME=?, DESCRIPTION=?, IS_PUBLIC=?, XML_QUERY=?, ");
        sqlStat.append("       RECORD_STATUS=?, UPDATE_COUNT=?, UPDATER_ID=?, UPDATE_DATE=? ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");

        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

        setPrepareStatement(preStat, 1, tmpQueryRecord.getUserRecordID());
        setPrepareStatement(preStat, 2, tmpQueryRecord.getQueryName());
        setPrepareStatement(preStat, 3, tmpQueryRecord.getDescription());
        setPrepareStatement(preStat, 4, tmpQueryRecord.getIsPublic());
        setPrepareStatement(preStat, 5, tmpQueryRecord.getXmlQuery());
        setPrepareStatement(preStat, 6, tmpQueryRecord.getRecordStatus());
        setPrepareStatement(preStat, 7, new Integer(tmpQueryRecord.getUpdateCount().intValue() + 1));
        setPrepareStatement(preStat, 8, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 9, currTime);
        setPrepareStatement(preStat, 10, tmpQueryRecord.getID());
        setPrepareStatement(preStat, 11, tmpQueryRecord.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          tmpQueryRecord.setUpdaterID(sessionContainer.getUserRecordID());
          tmpQueryRecord.setUpdateDate(currTime);
          tmpQueryRecord.setUpdateCount(new Integer(tmpQueryRecord.getUpdateCount().intValue() + 1));
          tmpQueryRecord.setCreatorName(UserInfoFactory.getUserFullName(tmpQueryRecord.getCreatorID()));
          tmpQueryRecord.setUpdaterName(UserInfoFactory.getUserFullName(tmpQueryRecord.getUpdaterID()));
          return (tmpQueryRecord);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_UPDATE_ERROR, e);
      } finally {
        try {
          preStat.close();
        } catch (Exception ignore) {} finally {
          preStat = null;
        }
      }
    }
  }

  protected synchronized AbstractBaseObject delete(AbstractBaseObject obj) throws
    ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    DmsQueryRecord tmpQueryRecord = (DmsQueryRecord) ( (DmsQueryRecord) obj).clone();

    synchronized (dbConn) {
      try {
        int updateCnt = 0;
        sqlStat.append("DELETE ");
        sqlStat.append("FROM   DMS_QUERY_RECORD ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpQueryRecord.getID());
        setPrepareStatement(preStat, 2, tmpQueryRecord.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          return (tmpQueryRecord);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_DELETE_ERROR, e);
      } finally {
        try {
          preStat.close();
        } catch (Exception ignore) {} finally {
          preStat = null;
        }
      }
    }
  }

  protected synchronized void auditTrail(String opMode, AbstractBaseObject obj) throws
    ApplicationException {
    Vector oldValues = new Vector();
    Vector newValues = new Vector();
    DmsQueryRecord tmpQueryRecord = (DmsQueryRecord) ( (DmsQueryRecord) obj).clone();

    if (tmpQueryRecord != null) {
      oldValues.add(toAuditTrailValue(tmpQueryRecord.getID()));
      oldValues.add(toAuditTrailValue(tmpQueryRecord.getUserRecordID()));
      oldValues.add(toAuditTrailValue(tmpQueryRecord.getQueryName()));
      oldValues.add(toAuditTrailValue(tmpQueryRecord.getDescription()));
      oldValues.add(toAuditTrailValue(tmpQueryRecord.getIsPublic()));
      oldValues.add(toAuditTrailValue(tmpQueryRecord.getXmlQuery()));
      oldValues.add(toAuditTrailValue(tmpQueryRecord.getRecordStatus()));
      oldValues.add(toAuditTrailValue(tmpQueryRecord.getUpdateCount()));
      oldValues.add(toAuditTrailValue(tmpQueryRecord.getCreatorID()));
      oldValues.add(toAuditTrailValue(tmpQueryRecord.getCreateDate()));
      oldValues.add(toAuditTrailValue(tmpQueryRecord.getUpdaterID()));
      oldValues.add(toAuditTrailValue(tmpQueryRecord.getUpdateDate()));
    }

    tmpQueryRecord = (DmsQueryRecord) obj;
    if (tmpQueryRecord != null) {
      newValues.add(toAuditTrailValue(tmpQueryRecord.getID()));
      newValues.add(toAuditTrailValue(tmpQueryRecord.getUserRecordID()));
      newValues.add(toAuditTrailValue(tmpQueryRecord.getQueryName()));
      newValues.add(toAuditTrailValue(tmpQueryRecord.getDescription()));
      newValues.add(toAuditTrailValue(tmpQueryRecord.getIsPublic()));
      newValues.add(toAuditTrailValue(tmpQueryRecord.getXmlQuery()));
      newValues.add(toAuditTrailValue(tmpQueryRecord.getRecordStatus()));
      newValues.add(toAuditTrailValue(tmpQueryRecord.getUpdateCount()));
      newValues.add(toAuditTrailValue(tmpQueryRecord.getCreatorID()));
      newValues.add(toAuditTrailValue(tmpQueryRecord.getCreateDate()));
      newValues.add(toAuditTrailValue(tmpQueryRecord.getUpdaterID()));
      newValues.add(toAuditTrailValue(tmpQueryRecord.getUpdateDate()));
    }

    auditTrailBase(opMode, oldValues, newValues);
  }

  /***********************************************************************
   * DON'T Modify the codes above unless you know what you are doing!!!  *
   * Put your own functions beblow.                                      *
   * For FINDER methods, the function name should be in the notation:    *
   *   public Object getObjectBy<Criteria>()                             *
   *   - e.g. public Object getObjectByCode()                            *
   *   public List getListBy<Criteria>()                                 *
   *   - e.g. public List getListByUserID()                              *
   * For OPERATION methods, the function name should be in the notation: *
   *   public void <Operation>ObjectBy<Criteria>()                       *
   *   - e.g. public void deleteObjectByCode()                           *
   *   public void <Operation>ListBy<Criteria>()                         *
   *   - e.g. public void deleteListByUserID()                           *
   ***********************************************************************/
  
  /**
   * Gets the list of the DmsQueryRecord object by query name.
   * 
   * @param queryName the name of query
   * @param isPublic  true, if is pullic, false then is private only the user create the query can use it.
   * @return the list of the DmsQueryRecord objects
   * @throws ApplicationException
   */
  public synchronized AbstractBaseObject getListByQueryName(String queryName,String isPublic) throws ApplicationException{
    return this.getListByQueryName(queryName,isPublic,null); 
  }
  
  public synchronized AbstractBaseObject getListByQueryName(String queryName,String isPublic,Integer userRecordID) throws ApplicationException{
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    Timestamp currTime = Utility.getCurrentTimestamp();
    Timestamp oneDayBeforeCurrTime = Utility.addDay(currTime, -1);
    synchronized (dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.USER_RECORD_ID, A.QUERY_NAME, A.DESCRIPTION, A.IS_PUBLIC, A.XML_QUERY, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   DMS_QUERY_RECORD A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? AND QUERY_NAME = ? AND IS_PUBLIC =? ");
        if(!Utility.isEmpty(userRecordID)){
          sqlStat.append("AND CREATOR_ID=? "); 
        }
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, queryName);
        this.setPrepareStatement(preStat, 3, isPublic);
        if(!Utility.isEmpty(userRecordID)){
          this.setPrepareStatement(preStat, 4, userRecordID);
        }
        rs = preStat.executeQuery();
        if (rs.next()) {
          DmsQueryRecord tmpDmsQueryRecord = new DmsQueryRecord();
          tmpDmsQueryRecord.setID(getResultSetInteger(rs, "ID"));
          tmpDmsQueryRecord.setUserRecordID(getResultSetInteger(rs, "USER_RECORD_ID"));
          tmpDmsQueryRecord.setQueryName(getResultSetString(rs, "QUERY_NAME"));
          tmpDmsQueryRecord.setDescription(getResultSetString(rs, "DESCRIPTION"));
          tmpDmsQueryRecord.setIsPublic(getResultSetString(rs, "IS_PUBLIC"));
          tmpDmsQueryRecord.setXmlQuery(getResultSetObject(rs, "XML_QUERY"));
          tmpDmsQueryRecord.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpDmsQueryRecord.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpDmsQueryRecord.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpDmsQueryRecord.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpDmsQueryRecord.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpDmsQueryRecord.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpDmsQueryRecord.setCreatorName(UserInfoFactory.getUserFullName(tmpDmsQueryRecord.getCreatorID()));
          tmpDmsQueryRecord.setUpdaterName(UserInfoFactory.getUserFullName(tmpDmsQueryRecord.getUpdaterID()));
          return tmpDmsQueryRecord;
        }else{
          return null;
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try {
          rs.close();
        } catch (Exception ignore) {} finally {
          rs = null;
        }
        try {
          preStat.close();
        } catch (Exception ignore) {} finally {
          preStat = null;
        }
      }
    }
  }
}